import { message } from 'antd';
import { DATA_UNIT_TYPES } from 'src/pages/AnalyseManage/EditReport/components/EditorDataType/EnumConfig';

/**
 * @param {object} obj 对象
 * @returns {object} 处理后的对象
 * @description 过滤掉对象中的null/undefined/''
 */
export const filterObjectNullKeys = ( obj ) => {
	let param = {};
	if ( obj === null || obj === undefined || obj === '' ) return param;
	for ( let key in obj ) {
		if ( obj[ key ] !== null && obj[ key ] !== undefined && obj[ key ] !== '' ) {
			param[ key ] = obj[ key ];
		}
	}
	return param;
};

/**
 * 防抖函数
 * @param {Function} fun 函数
 * @param {Number} delay 延时时间
 */
export const debounce = ( fun, delay ) => {
	return function ( args ) {
		let that = this;
		let _args = args;
		clearTimeout( fun.id );
		fun.id = setTimeout( function () {
			fun.call( that, _args );
		}, delay );
	};
};

// 日期格式化方法
export function dateFormat( date, formatString ) {
	if ( !date ) {
		return '';
	}

	date = new Date( date );

	// 替换规则
	let rules = {
		'M+': date.getMonth() + 1, // 月份
		'd+': date.getDate(), // 日
		'h+': date.getHours(), // 小时
		'm+': date.getMinutes(), // 分
		'q+': Math.floor( ( date.getMonth() + 3 ) / 3 ), // 季度
		's+': date.getSeconds(), // 秒
		'w': '日一二三四五六'.charAt( date.getDay() ), // 星期
		'S': date.getMilliseconds() // 毫秒
	};
	// 年
	if ( /([y|Y]+)/.test( formatString ) ) {
		formatString = formatString.replace( RegExp.$1, ( `${date.getFullYear()}` ).substr( 4 - RegExp.$1.length ) );
	}

	// 规则替换
	for ( let type in rules ) {
		if ( new RegExp( `(${ type })` ).test( formatString ) ) {
			formatString = formatString.replace( RegExp.$1, ( RegExp.$1.length === 1 ) ? ( rules[ type ] ) : ( ( `00${rules[ type ]}` ).substr( ( `${rules[ type ]}` ).length ) ) );
		}
	}
	return formatString;
}

//	判断是否是数字，包括数字类型和字符串数字
export function isNumber( val ) {

	const regPos = /^\d+(\.\d+)?$/; //非负浮点数
	const regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
	if ( regPos.test( val ) || regNeg.test( val ) ) {
		return true;
	} else {
		return false;
	}

}

//	数字以位数分割
//	@param value 需要分割的数字
//  @param digit 几位一分，例如3就是分成千分位
export function digitFormat( value, digit ) {

	let valueUp = value;

	if ( !isNumber( value ) ) return value;
	// if( Object.prototype.toString.call( value ) !== '[object Number]' || Number( value ) === 0 ) return value;

	//fix '-0.58'这种小于0大于-1的，经过parseInt(valueUp).toFixed(0)会miss负号，所以手动添加负号
	let intPart = ( value < 0 && value > -1 ) ? `-${parseInt( valueUp ).toFixed( 0 )}` : parseInt( valueUp ).toFixed( 0 );
	//获取整数部分
	const reg = new RegExp( `(\\d)(?=(?:\\d{${ digit }})+$)`, 'g' );
	let intPartFormat = intPart.toString().replace( reg, '$1,' );
	//将整数部分逢三一断
	let floatPart = '';
	//预定义小数部分
	let value2Array = value.toString().split( '.' );
	//=2表示数据有小数位
	if ( value2Array.length >= 2 ) {
		floatPart = value2Array[ 1 ];
		//拿到小数部分

		return `${intPartFormat}.${floatPart}`;

	} else {
		return intPartFormat + floatPart;
	}
}

//	数字万分位
export function tenThousandFormat( num ) {
	if ( isNaN( num ) || Number( num ) === 0 ) return num;
	const reg = /\d{1,4}(?=(\d{4})+$)/g;
	return ( `${num}` ).replace( reg, '$&,' );
}

/**
 * 将大额数值转换为带单位的数值（千，万等）
 * @param {*} date
 * @param {*} formatString
 */
export const bigNumberTransform = ( value ) => {
	const newValue = [ '', '', '' ];
	// value = parseInt( value.replace( /[^0-9]/g, '' ) );
	let fr = 1000;
	let num = 3;
	let text1 = '';
	let fm = 1;
	while ( value / fr >= 1 ) {
		fr *= 10;
		num += 1;
		// console.log('数字', value / fr, 'num:', num)
	}
	if ( num <= 4 ) { // 千
		newValue[ 0 ] = `${parseInt( value / 1000 )}`;
		newValue[ 1 ] = '千';
	} else if ( num <= 8 ) { // 万
		text1 = parseInt( num - 4 ) / 3 > 1 ? '千万' : '万';
		// tslint:disable-next-line:no-shadowed-variable
		fm = text1 === '万' ? 10000 : 10000000;
		if ( value % fm === 0 ) {
			newValue[ 0 ] = `${parseInt( value / fm )}`;
		} else {
			newValue[ 0 ] = `${parseFloat( value / fm ).toFixed( 2 )}`;
		}
		newValue[ 1 ] = text1;
	} else if ( num <= 16 ) { // 亿
		text1 = ( num - 8 ) / 3 > 1 ? '千亿' : '亿';
		text1 = ( num - 8 ) / 4 > 1 ? '万亿' : text1;
		text1 = ( num - 8 ) / 7 > 1 ? '千万亿' : text1;
		// tslint:disable-next-line:no-shadowed-variable
		fm = 1;
		if ( text1 === '亿' ) {
			fm = 100000000;
		} else if ( text1 === '千亿' ) {
			fm = 100000000000;
		} else if ( text1 === '万亿' ) {
			fm = 1000000000000;
		} else if ( text1 === '千万亿' ) {
			fm = 1000000000000000;
		}
		if ( value % fm === 0 ) {
			newValue[ 0 ] = `${parseInt( value / fm )}`;
		} else {
			newValue[ 0 ] = `${parseFloat( value / fm ).toFixed( 2 )}`;
		}
		newValue[ 1 ] = text1;
	}
	if ( value < 1000 ) {
		newValue[ 0 ] = `${value}`;
		newValue[ 1 ] = '';
	}
	return newValue.join( '' );
};

// 递归查找 resource
export const getResourceIdByPath = ( menu, path ) => {

	for ( let key = 0; key < menu.length; key++ ) {
		if ( menu[ key ].uri === path ) {
			return menu[ key ];
		}
		if ( menu[ key ].childrenList ) {
			let resource = getResourceIdByPath( menu[ key ].childrenList, path );
			if ( resource ) return resource;
		}
	}
	return null;
};

/**
 * 映射tree所需的字段
 * @param {*} treeNode 树节点
 * 示例: res.data.data.map( treeNode => mapTreeData( treeNode ) );
 */
export const mapTreeData = ( treeNode ) => {
	const haveChildren = Array.isArray( treeNode.children ) && treeNode.children.length > 0;
	return {
		...treeNode,
		title: treeNode.name,
		key: treeNode.id || Math.random(),
		children: haveChildren ? treeNode.children.map( i => mapTreeData( i ) ) : []
	};
};

/**
 * 树状结构转平级结构
 * @param {*} treeData 树数据
 * 示例: res.data.data.map( treeNode => mapTreeData( treeNode ) );
 */
export const transformTreeData = ( compressedData, treeData ) => {
	for ( let i in treeData ) {
		compressedData.push( treeData[ i ] );
		// eslint-disable-next-line no-unused-expressions
		treeData[ i ].children && treeData[ i ].children.length > 0 ? transformTreeData( compressedData, treeData[ i ].children ) : '';// 子级递归
	}
	return compressedData;
};

/**
 * 复制按钮
 * @param {*} id dom id
 *
 */
export const copyTranslateResult = ( id ) => {
	const copyDOM = document.querySelector( id );
	if ( copyDOM.value || copyDOM.innerText ) {
		let range = document.createRange(); // 创建一个range
		window.getSelection().removeAllRanges(); // 清除页面中已有的selection
		range.selectNode( copyDOM ); // 选中需要复制的节点
		window.getSelection().addRange( range ); // 执行选中元素
		let successful = document.execCommand( 'copy' ); // 执行 copy 操作
		if ( successful ) {
			message.success( '复制成功！' );
		} else {
			message.warning( '复制失败，请手动复制！' );
		}
		// 移除选中的元素
		window.getSelection().removeAllRanges();
	} else {
		message.warning( '没有内容' );
	}
};

/**
 * 数据单位数据转换
 */
export const transformDataUnitData = ( data, dataUnits, valueField, originValueField = valueField ) => {
	// const originField = originValueField ? originValueField : valueField;
	const newData = data.map( ( v ) => {
		const categorys = ( v.category && v.category.split( '-' ) ) || [];
		const category = categorys[ categorys.length - 1 ];
		const item = dataUnits.length === 1 ? dataUnits[ 0 ] : dataUnits.find( i => i.alias.trim() === category );

		let unit = item && item.dataUnit ? DATA_UNIT_TYPES[ item.dataUnit ].label : '';
		return {
			...v,
			[ valueField ]: v[ originValueField ] && unit ? `${v[ originValueField ]}${unit || ''}` : v[ originValueField ],
		};
	} );
	return newData;
};

//	取区间随机数
export const getRandom = ( min, max ) => {
	return Math.floor( Math.random() * ( max - min + 1 ) + min );
};

//	获取当前环境
export const getEnv = () => {
	const envs = [ 'local', 'dev', 'test', 'demo', 'prod' ];
	let env = '';
	const location = window.location.href;

	envs.some( v => {
		if ( location.indexOf( v ) > -1 ) {
			env = v;
			return true;
		}
		return false;
	} );

	return env;
};

//	在数组树结构中找到第一张表
//	深度优先遍历算法
export const getFirstTable = ( tables ) => {
	let tableCode = '';

	tables.some( file => {
		if ( file.isFile === '0' ) {
			tableCode = file.code;
			return true;
		} else if ( file.children && file.children.length > 0 ) {
			tableCode = getFirstTable( file.children );
			if ( tableCode ) return true;
		}
		return false;
	} );

	return tableCode;
};

//	根据表modelId， 查找表名
export const getTableName = ( tables, modelId ) => {
	let tableName = '';

	tables.some( table => {
		if ( table.code === modelId ) {
			tableName = table.title;
			return true;
		} else if ( table.children && table.children.length > 0 ) {
			tableName = getTableName( table.children, modelId );
			if ( tableName ) return true;
		}
		return false;
	} );

	return tableName;

};